package com.centit.task;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.centit.airplanebaseinfo.po.AirplaneBaseinfo;
import com.centit.airplanebaseinfo.po.SMSUtils;
import com.centit.airplanebaseinfo.service.AirplaneBaseinfoManager;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.framework.components.OperationLogCenter;
import com.centit.framework.model.basedata.IDataDictionary;
import com.centit.framework.model.basedata.IUserInfo;
import com.centit.support.algorithm.UuidOpt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Component
@EnableScheduling
public class SendSmsTask {
    @Resource
    private AirplaneBaseinfoManager airplaneBaseinfoMag;

    @Scheduled(cron = "0 0 08 * * ? ")//下午五点发送明天的短信2.30
    public void sendJhdxyjSms() {
        try {
            //计划大修预警
            JSONArray jsonArray= allData("jhdx");
            jsonArray.stream().forEach(o->{
                JSONObject jsonObject=(JSONObject)o;
                AirplaneBaseinfo airplaneBaseinfo=airplaneBaseinfoMag.getObjectById(jsonObject.getString("recId"));
                if(jsonObject.containsKey("lastSendDaysJh")&&
                        StringUtils.isNotEmpty(jsonObject.getString("lastSendDaysJh"))){
                    //一个月发一次
                    int lastSendDays=jsonObject.getIntValue("lastSendDaysJh");
                    if(lastSendDays+1>30){
                        //发送短信
                        airplaneBaseinfo.setLastSendDaysJh("1");
                        airplaneBaseinfoMag.updateObject(airplaneBaseinfo);
                        StringBuilder msgContent=new StringBuilder();
                        msgContent.append("计划大修提醒短信：注册号为"+airplaneBaseinfo.getSign()+
                                "航空器型号"+airplaneBaseinfo.getAirModel()+"的机队计划大修时间" +
                                "距离退租时间已不足半年，剩余天数："+jsonObject.getString("tzrqqbnnjhdxDays")+"，请注意维护。");
                        List<IDataDictionary> iDataDictionaryList=(List<IDataDictionary>)CodeRepositoryUtil.getDictionary("JHDXYJ_PHONE");

                        for(IDataDictionary iDataDictionary:iDataDictionaryList){
                            if(StringUtils.isNotEmpty(iDataDictionary.getDataValue())){
                                SMSUtils.sendMsg(iDataDictionary.getDataValue(),msgContent.toString(),SMSUtils.templateIdJh);
                            }else {
                                OperationLogCenter.logNewObject("timeTask", "SendSmsTask", UuidOpt.getUuidAsString32(),
                                        "sendJhdxyjSms","计划大修预警发送短信未找到手机号",  iDataDictionary);
                            }
                        }

                    }else{
                        lastSendDays++;
                        airplaneBaseinfo.setLastSendDaysJh(String.valueOf(lastSendDays));
                        airplaneBaseinfoMag.updateObject(airplaneBaseinfo);
                    }

                }else {
                    airplaneBaseinfo.setLastSendDaysJh("1");
                    airplaneBaseinfoMag.updateObject(airplaneBaseinfo);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            //预期大修预警
            JSONArray jsonArray= allData("yqdx");
            jsonArray.stream().forEach(o->{
                JSONObject jsonObject=(JSONObject)o;
                AirplaneBaseinfo airplaneBaseinfo=airplaneBaseinfoMag.getObjectById(jsonObject.getString("recId"));
                if(jsonObject.containsKey("lastSendDaysYq")&&
                        StringUtils.isNotEmpty(jsonObject.getString("lastSendDaysYq"))){
                    //一个月发一次
                    int lastSendDays=jsonObject.getIntValue("lastSendDaysYq");
                    if(lastSendDays+1>30){
                        //发送短信
                        airplaneBaseinfo.setLastSendDaysYq("1");
                        airplaneBaseinfoMag.updateObject(airplaneBaseinfo);
                        StringBuilder msgContent=new StringBuilder();
                        msgContent.append("预期大修提醒短信：注册号为"+airplaneBaseinfo.getSign()+
                                "航空器型号"+airplaneBaseinfo.getAirModel()+"的机队预期大修时间Q1或Q2" +
                                "距离退租时间已不足半年，剩余天数："+jsonObject.getString("tzrqqbnnjhdxDays")+"，请注意维护。");
                        List<IDataDictionary> iDataDictionaryList=(List<IDataDictionary>)CodeRepositoryUtil.getDictionary("YQDXYJ_PHONE");

                        for(IDataDictionary iDataDictionary:iDataDictionaryList){
                            if(StringUtils.isNotEmpty(iDataDictionary.getDataValue())){
                                SMSUtils.sendMsg(iDataDictionary.getDataValue(),msgContent.toString(),SMSUtils.templateIdYq);
                            }else {
                                OperationLogCenter.logNewObject("timeTask", "SendSmsTask", UuidOpt.getUuidAsString32(),
                                        "sendJhdxyjSms","预期大修预警发送短信未找到手机号",  iDataDictionary);
                            }
                        }

                    }else{
                        lastSendDays++;
                        airplaneBaseinfo.setLastSendDaysYq(String.valueOf(lastSendDays));
                        airplaneBaseinfoMag.updateObject(airplaneBaseinfo);
                    }

                }else {
                    airplaneBaseinfo.setLastSendDaysYq("1");
                    airplaneBaseinfoMag.updateObject(airplaneBaseinfo);
                }
            });

        }catch (Exception e){
            e.printStackTrace();
        }

        try {
            //电台执照监控报警
            JSONArray jsonArray= allData("dtzz");
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            jsonArray.stream().forEach(o->{
                JSONObject jsonObject=(JSONObject)o;
                AirplaneBaseinfo airplaneBaseinfo=airplaneBaseinfoMag.getObjectById(jsonObject.getString("recId"));
                if(jsonObject.containsKey("lastSendDaysDtzz")&&
                        StringUtils.isNotEmpty(jsonObject.getString("lastSendDaysDtzz"))){
                    //七天发一次
                    int lastSendDays=jsonObject.getIntValue("lastSendDaysDtzz");
                    if(lastSendDays+1>7){
                        //发送短信
                        airplaneBaseinfo.setLastSendDaysDtzz("1");
                        airplaneBaseinfoMag.updateObject(airplaneBaseinfo);
                        StringBuilder msgContent=new StringBuilder();
                        msgContent.append("电台执照监控报警短信：注册号为"+airplaneBaseinfo.getSign()+
                                "航空器型号"+airplaneBaseinfo.getAirModel()+"的电台执照已过报警日期：" +sdf.format(airplaneBaseinfo.getDtzzjkbjrq())+
                                "超期天数："+jsonObject.getString("dtzzCqts")+"，请注意维护。");
                        List<IDataDictionary> iDataDictionaryList=(List<IDataDictionary>)CodeRepositoryUtil.getDictionary("DTZZJKYJ_PHONE");

                        for(IDataDictionary iDataDictionary:iDataDictionaryList){
                            if(StringUtils.isNotEmpty(iDataDictionary.getDataValue())){
                                SMSUtils.sendMsg(iDataDictionary.getDataValue(),msgContent.toString(),SMSUtils.templateIdDtzz);
                            }else {
                                OperationLogCenter.logNewObject("timeTask", "SendSmsTask", UuidOpt.getUuidAsString32(),
                                        "sendJhdxyjSms","电台执照监控报警发送短信未找到手机号",  iDataDictionary);
                            }
                        }

                    }else{
                        lastSendDays++;
                        airplaneBaseinfo.setLastSendDaysDtzz(String.valueOf(lastSendDays));
                        airplaneBaseinfoMag.updateObject(airplaneBaseinfo);
                    }

                }else {
                    airplaneBaseinfo.setLastSendDaysDtzz("1");
                    airplaneBaseinfoMag.updateObject(airplaneBaseinfo);
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    private JSONArray allData(String type){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        if("jhdx".equals(type)){
            Map<String, Object> searchColumn =new HashMap<>();
            searchColumn.put("dataValid", "T");
            searchColumn.put("tzrqqbnnjhdx", "预警");
            JSONArray jsonArrayObjects = airplaneBaseinfoMag.listObjectsAsJson(searchColumn, null);

            jsonArrayObjects.stream().forEach(o->{
                JSONObject jsonObject=(JSONObject)o;
                //间隔时间
                long daysDiff=0;
                try {
                    LocalDate date2 = LocalDate.parse(sdf.format(jsonObject.getDate("endTime")));
                    LocalDate date1 = LocalDate.parse(sdf.format(jsonObject.getDate("jhdxxyckssjT")));
                    daysDiff = ChronoUnit.DAYS.between(date1, date2);
                }catch (Exception e){
                    e.printStackTrace();
                }

                jsonObject.put("tzrqqbnnjhdxDays",daysDiff);
            });

            return jsonArrayObjects;
        }else if("yqdx".equals(type)){
            Map<String, Object> searchColumn =new HashMap<>();
            searchColumn.put("dataValid", "T");
            searchColumn.put("tzrqqbnnyqdx", "预警");
            JSONArray jsonArrayObjects = airplaneBaseinfoMag.listObjectsAsJson(searchColumn, null);

            jsonArrayObjects.stream().forEach(o->{
                JSONObject jsonObject=(JSONObject)o;
                //间隔时间
                long daysDiff=0;
                long daysDiff2=0;
                try {
                    LocalDate date1 = LocalDate.parse(sdf.format(jsonObject.getDate("endTime")));
                    LocalDate date2 = LocalDate.parse(sdf.format(jsonObject.getDate("dxksslQ1")));
                    LocalDate date3 = LocalDate.parse(sdf.format(jsonObject.getDate("dxkssjQ2")));
                    daysDiff = ChronoUnit.DAYS.between(date2,date1);
                    daysDiff2 = ChronoUnit.DAYS.between(date3,date1);
                }catch (Exception e){
                    e.printStackTrace();
                }

                jsonObject.put("tzrqqbnnjhdxDays",daysDiff+","+daysDiff2);
            });

            return jsonArrayObjects;
        }else {
            //默认电台执照
            Map<String, Object> searchColumn =new HashMap<>();
            searchColumn.put("dataValid", "T");
            Date today=new Date();
            searchColumn.put("dtzzjkbjrq",sdf.format(today));

            JSONArray newJson= airplaneBaseinfoMag.listObjectsAsJson( searchColumn, null);


            newJson.stream().forEach(o->{
                JSONObject jsonObject=(JSONObject)o;
                long daysDiff=0;
                try {

                    jsonObject.put("dtzzjkbjDate",sdf.format(jsonObject.getDate("dtzzjkbjrq")));
                    LocalDate date2 = LocalDate.parse(sdf.format(today));
                    LocalDate date1 = LocalDate.parse(sdf.format(jsonObject.getDate("dtzzjkbjrq")));
                    daysDiff = ChronoUnit.DAYS.between(date1, date2);

                }catch (Exception e){
                    e.printStackTrace();
                    daysDiff=0l;
                }

                jsonObject.put("dtzzCqts",daysDiff);

            });
            System.out.println("--------newJson-------"+ JSON.toJSONString(newJson));
            return newJson;
        }

    }

}
